package com.wb.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File
import java.util.*
import javax.xml.bind.DatatypeConverter
import kotlin.collections.HashMap
import kotlin.jvm.Throws

class XiGuaVideo {

    companion object {

        @Throws(Exception::class)
        fun search(key: String, savePath: String): File? {

            val url =
                "https://www.ixigua.com/search/${key}/?logTag=${UUID.randomUUID()}&tab_name=search&order_type=publish_time"

            var dom = RestUtil.getPage(url, null)

            if (dom == null) {
                return null
            }

            val list = dom.select(".HorizontalFeedCard")

            if (list == null || list.size == 0) {
                return null
            }

            val element = list.get(
                (Math.random() * list.size).toInt()
            )

            val href = element.selectFirst("a").attr("href")

            val infoUrl = "https://www.ixigua.com" + href
            dom = RestUtil.getPage(
                infoUrl, null
            )

            val title = dom?.selectFirst(".videoTitle")?.text()

            println(infoUrl)
            println(element.select(".HorizontalFeedCard__title").text())
            println(list.map { it.select(".HorizontalFeedCard__title").text() })

            val ssrData = dom?.select("#SSR_HYDRATED_DATA")?.html()
                ?.replace("window._SSR_HYDRATED_DATA=", "")
                ?.replace("//]]>", "")
                ?.replace("//<![CDATA[", "")

            if (!ssrData.isNullOrBlank()) {

                val gson = Gson()

                var map = gson.fromJson(
                    ssrData,
                    object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                map = gson.fromJson(
                    gson.toJson(map.get("anyVideo")), object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                map = gson.fromJson(
                    gson.toJson(map.get("gidInformation")), object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                map = gson.fromJson(
                    gson.toJson(map.get("packerData")), object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                map = gson.fromJson(
                    gson.toJson(map.get("video")), object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                val videoResourceMap = gson.fromJson(
                    gson.toJson(map.get("videoResource")), object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                map = gson.fromJson(
                    gson.toJson(
                        videoResourceMap.get("normal")
                    ), object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                map = gson.fromJson(
                    gson.toJson(map.get("video_list")), object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                var videoKey = "video_3"
                if (map.containsKey("video_3") && map.get("video_3") != null) {
                    videoKey = "video_3"
                } else if (map.containsKey("video_2") && map.get("video_2") != null) {
                    videoKey = "video_2"
                } else {
                    videoKey = "video_1"
                }
                map = gson.fromJson(
                    gson.toJson(map.get(videoKey)), object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                val mainUrl = map.get("main_url").toString()

                // 解密base64
                var videoUrl = String(DatatypeConverter.parseBase64Binary(mainUrl))
                if (!videoUrl.startsWith("http")) {
                    videoUrl = "http:${videoUrl}"
                }

                val fileName = "${title}_${
                    when (videoKey) {
                        "video_3" -> "720p"
                        "video_2" -> "480p"
                        else -> "360p"
                    }
                }.mp4"
                FileNetUtil.downHttpUrl(videoUrl, savePath, fileName)
                return File(savePath, fileName)
            }

            return null
        }

    }

}

fun main() {
    try {
        XiGuaVideo.search("美女", "C:\\Users\\76167\\Desktop\\文档数据\\test")
    } catch (e: Exception) {
        e.printStackTrace()
    }
}